<template>
  <div class="instrument_list_wrap">
    <!-- 查询表单 -->
    <el-card class="query_form_card">
      <el-form style="height: 30px" :inline="true" :model="queryFormData" class="demo-form-inline">
        <el-form-item>
          <template #label>
            <i class="iconfont icon-bianhao"></i>
            <span>仪器编号</span>
          </template>
          <el-input v-model="queryFormData.devCode" placeholder="请输入编号" clearable />
        </el-form-item>
        <el-form-item>
          <template #label>
            <i class="iconfont icon-yiqihecha"></i>
            <span>仪器名称</span>
          </template>
          <el-input v-model="queryFormData.devName" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="queryClick">查询</el-button>
          <el-button type="primary" :icon="Plus" @click="addInstrumentClick">添加仪器</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 仪器列表 -->
    <el-card class="instrument_table_card">
      <div class="table_box">
        <el-table :data="instrumentList" v-loading="isTableLoading" stripe>
          <el-table-column prop="num" label="序号" align="center" width="100" />
          <el-table-column prop="devCode" label="编号" align="center" />
          <el-table-column prop="devName" label="名称" align="center" />
          <el-table-column prop="devType" label="型号" align="center" />
          <el-table-column prop="devUnit" label="领用单位" align="center" width="240" />
          <el-table-column prop="devHome" label="存放地" align="center" width="240" />
          <el-table-column prop="devStatus" label="现状" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.devStatus == 1" type="success">在用</el-tag>
              <el-tag v-if="scope.row.devStatus == 0" type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="devStoreTime" label="入库日期" align="center" />
          <el-table-column prop="devDesc" label="备注" align="center" />
          <el-table-column prop="labDesc" label="操作" align="center" width="160">
            <template #default="scope">
              <el-button type="primary" :icon="Edit" @click="editInstrumentClick(scope.row)" link>编辑</el-button>
              <el-popconfirm title="确定要删除此仪器吗?" @confirm="delInstrumentClick(scope.row)">
                <template #reference>
                  <el-button type="danger" :icon="Delete" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="tab_pagination"
          background
          layout="prev, pager, next"
          v-model:current-page="queryFormData.page"
          v-model:page-size="queryFormData.size"
          :total="tableTotal"
          @change="paginationChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="isShowAddEditInstrumentDialog"
      :title="`${addEditInstrumentFormData.devId ? '编辑' : '添加'}仪器`"
      width="500"
      :before-close="addEditInstrumentDialogCancelClick"
    >
      <div class="add_edit_instrument_dialog_box">
        <div class="add_edit_instrument_form_item_box">
          <el-form
            ref="addEditInstrumentFormRef"
            :rules="addEditRules"
            :model="addEditInstrumentFormData"
            label-width="auto"
            class="demo-ruleForm"
          >
            <!--   -->
            <el-form-item label="编号" prop="devCode">
              <el-input v-model="addEditInstrumentFormData.devCode" style="width: 280px" placeholder="请输入编号" />
            </el-form-item>
            <el-form-item label="名称" prop="devName">
              <el-input v-model="addEditInstrumentFormData.devName" style="width: 280px" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="型号" prop="devType">
              <el-input v-model="addEditInstrumentFormData.devType" style="width: 280px" placeholder="请输入型号" />
            </el-form-item>
            <el-form-item label="领用单位" prop="devUnit">
              <el-input v-model="addEditInstrumentFormData.devUnit" style="width: 280px" placeholder="请输入领用单位" />
            </el-form-item>
            <el-form-item label="现状" prop="devStatus">
              <el-radio-group class="add_edit_dev_status_radio" v-model="addEditInstrumentFormData.devStatus">
                <el-radio :value="1">
                  <el-tag type="success">在用</el-tag>
                </el-radio>
                <el-radio :value="0">
                  <el-tag type="danger">停用</el-tag>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="存放地" prop="devHome">
              <el-input
                v-model="addEditInstrumentFormData.devHome"
                style="width: 280px"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入存放地"
              />
            </el-form-item>

            <el-form-item label="备注" prop="devDesc">
              <el-input
                v-model="addEditInstrumentFormData.devDesc"
                style="width: 280px"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
          <!-- <span class="label">实验室房间号:</span>
          <el-input v-model="addEditFormData.laboratoryHome" style="width: 240px" placeholder="请输入实验室房间号" /> -->
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditInstrumentDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="addEditInstrumentDialogConfirmClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref } from "vue";
import { Search, Edit, Delete, Plus } from "@element-plus/icons-vue";
import "./index.scss";
import { message } from "ant-design-vue";
export default defineComponent({
  name: "InstrumentList"
});
</script>
<script lang="ts" setup>
import { instrumentListType } from "./type";
import { instruments } from "./data";
import { numComp } from "@/utils/table";
import { selectDevByPageApi, addDevApi, editDevApi, deleteDevApi } from "@/api/modules/instrumentList/index";
import _ from "lodash";
import type { FormRules } from "element-plus";
import { getDate } from "@/utils/date";

interface RuleForm {
  devCode: string;
  devName: string;
  devType: string;
  devUnit: string;
  devHome: string;
}

// 查询表单数据
const queryFormData = reactive({
  page: 1,
  size: 10,
  devCode: "",
  devName: ""
});

// 添加/编辑仪器表单数据
const addEditInstrumentFormData = ref({
  devId: null,
  devCode: "",
  devName: "",
  devType: "",
  devUnit: "",
  devHome: "",
  devStatus: "",
  devStoreTime: "",
  devDesc: ""
});

// 添加/编辑实验室表单校验规则
const addEditRules = reactive<FormRules<RuleForm>>({
  devCode: [{ required: true, message: "编号为必填项", trigger: "blur" }],
  devName: [{ required: true, message: "名称为必填项", trigger: "blur" }],
  devType: [{ required: true, message: "型号为必填项", trigger: "blur" }],
  devUnit: [{ required: true, message: "领用单位为必填项", trigger: "blur" }],
  devHome: [{ required: true, message: "存放地为必填项", trigger: "blur" }],
  devStatus: [{ required: true, message: "现状为必选项", trigger: "blur" }]
});

// 添加/编辑仪器表单Ref
const addEditInstrumentFormRef = ref(null);

// 表格数据总数
const tableTotal = ref(10);

// 表格加载标识
const isTableLoading = ref(false);

// 显示添加/编辑仪器弹窗的标识
const isShowAddEditInstrumentDialog = ref(false);

// 仪器列表
const instrumentList = ref<instrumentListType>(instruments);

// 删除仪器点击事件
const delInstrumentClick = row => {
  console.log(row);
  deleteDevFunc(row.devId);
};

// 删除请求函数
const deleteDevFunc = async devId => {
  let data = {
    devId: devId
  };
  await deleteDevApi(data)
    .then(res => {
      if (res.result == "success") {
        message.success("删除成功");
      } else if (res.result == "error") {
        message.error("删除失败");
      }
    })
    .finally(() => {
      selectDevByPageFunc();
    });
};

// 添加仪器点击事件
const addInstrumentClick = () => {
  isShowAddEditInstrumentDialog.value = true;
};

// 编辑仪器点击事件
const editInstrumentClick = row => {
  let instrument = _.cloneDeep(row);
  delete instrument.num;
  instrument.devStatus = Number(instrument.devStatus);
  console.log(instrument);
  addEditInstrumentFormData.value = instrument;
  isShowAddEditInstrumentDialog.value = true;
};

// 重置添加/编辑仪器弹窗表单
const resetAddEditInstrumentDialogFormData = () => {
  addEditInstrumentFormData.value = {
    devId: null,
    devCode: "",
    devName: "",
    devType: "",
    devUnit: "",
    devHome: "",
    devStatus: "",
    devStoreTime: "",
    devDesc: ""
  };

  if (!addEditInstrumentFormRef.value) return;
  addEditInstrumentFormRef.value.resetFields();
};

// 添加/编辑仪器弹窗确定点击事件
const addEditInstrumentDialogConfirmClick = () => {
  addEditInstrumentFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      if (addEditInstrumentFormData.value.devId) {
        editDevFunc();
        console.log("编辑");
      } else {
        addDevFunc();
        console.log("添加");
      }
      isShowAddEditInstrumentDialog.value = false;
      resetAddEditInstrumentDialogFormData();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 添加请求函数
const addDevFunc = async () => {
  let data = addEditInstrumentFormData.value;
  delete data.devId;
  data.devStoreTime = getDate();
  await addDevApi(data)
    .then(res => {
      if (res.result == "success") {
        isShowAddEditInstrumentDialog.value = false;
        message.success("添加成功");
      } else if (res.result == "error") {
        message.error("添加失败");
      }
    })
    .finally(() => {
      selectDevByPageFunc();
    });
};

// 编辑请求函数
const editDevFunc = async () => {
  let data = addEditInstrumentFormData.value;
  await editDevApi(data)
    .then(res => {
      if (res.result == "success") {
        isShowAddEditInstrumentDialog.value = false;
        message.success("修改成功");
      } else if (res.result == "error") {
        message.error("修改失败");
      }
    })
    .finally(() => {
      selectDevByPageFunc();
    });
};

// 添加/编辑仪器弹窗取消点击事件
const addEditInstrumentDialogCancelClick = () => {
  isShowAddEditInstrumentDialog.value = false;
  resetAddEditInstrumentDialogFormData();
};

// 处理表格序号
const disposeTableNum = () => {
  let page = queryFormData.page;
  let size = queryFormData.size;
  instrumentList.value.forEach((item, indexL) => {
    item.num = numComp(page, size, indexL);
  });
};

// 分页器change事件
const paginationChange = e => {
  queryFormData.page = e;
  selectDevByPageFunc();
};

// 查询仪器点击事件
const queryClick = () => {
  queryFormData.page = 1;
  selectDevByPageFunc();
};

// 查询表格数据
const selectDevByPageFunc = async () => {
  isTableLoading.value = true;
  await selectDevByPageApi(queryFormData)
    .then(res => {
      if (res.result == "success") {
        instrumentList.value = res.data.list;
        tableTotal.value = res.data.total;
        disposeTableNum();
      }
    })
    .finally(() => {
      isTableLoading.value = false;
    });
};

// init
onMounted(() => {
  selectDevByPageFunc();
});
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
